﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using T03ChatServer;

namespace T03ChatSever
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private Socket severSocket = null;
        //服务启动标志：控制启动
        private bool isListen = true;
        //字典保存多个用户名信息 key（用户名）value（socket）
        public Dictionary<string, Socket> clientList = null;
        public MainWindow()
        {
            InitializeComponent();
        }
        private void BtnStart_Click(Object sender, RoutedEventArgs e)
        {
            //监听（Accept）也需要新开发线程
            if (severSocket == null)
            {
                isListen = true;
                //初始化字典
                clientList = new Dictionary<string, Socket>();
                //服务器地址：测试使用本地地址127.0.0.1
                IPAddress ip = IPAddress.Parse("127.0.0.1");
                IPEndPoint iep = new IPEndPoint(ip, 18888);
                //创建SOCKET
                severSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //绑定
                severSocket.Bind(iep);
                //监听
                severSocket.Listen(100);
                //启动线程，开启服务相应
                Thread t = new Thread(StartListen);
                //后台运行模式
                t.IsBackground = true;
                t.Start();
                //提示信息，异步模式更新UI显示
                TxtMsg.Dispatcher.BeginInvoke(new Action(() => { TxtMsg.Text += "服务器启动...\r\n"; }));


            }

        }

        private void BtnStop_Click(Object sender, RoutedEventArgs e)
        {
            if (severSocket != null)
            {
                Broadcast.PushMessage("服务器即将关闭","",clientList,Broadcast.SYSTEM_MSG);
                //关闭所有客户端的连接
                foreach (var socket in clientList.Values)
                {
                    socket.Close();
                }
                //清空字典
                clientList.Clear();
                severSocket.Close();
                severSocket = null;
                //停止监听进程
                isListen = false;
                TxtMsg.Text += "服务停止!\r\n";
            }

        }
        //该函数是服务端SOCKET监听线程的委托函数
        private void StartListen()
        {
            //创建套接字
            Socket clientSocket = default(Socket);
            try
            {
                clientSocket = severSocket.Accept();
                //就创建数据缓存
                byte[] bytesFrom = new byte[4096];
                string dataFromClient = null;
                int len = clientSocket.Receive(bytesFrom);

                if (len > 0)
                {//客户端传来的数据（用户名）
                    dataFromClient = Encoding.UTF8.GetString(bytesFrom, 0, len);
                    //分析协议：“$”标志信息的完整性
                    int sublen = dataFromClient.LastIndexOf("$");
                    if (sublen > -1)
                    { //数据合法
                      //分割，获取有效数据
                        dataFromClient = dataFromClient.Substring(0, sublen);
                        if (!clientList.ContainsKey(dataFromClient))
                        {
                            //加入字典
                            clientList.Add(dataFromClient, clientSocket);
                            //广播新用户的信息
                            Broadcast.PushMessage(dataFromClient+"加入",dataFromClient,clientList,Broadcast.SYSTEM_MSG);
                            //开启客户端连接线程
                            new HandleClient().StartClient(clientSocket,dataFromClient,clientList);

                        }
                        else
                        {
                            //如果已经存在用户，向客户端发送消息
                            clientSocket.Send(Encoding.UTF8.GetBytes("#" + dataFromClient + "#"));
                        }
                    }
                }
            }
            catch (Exception e)
            {
                if (clientSocket != null && !clientSocket.Connected)
                {
                    clientSocket.Close();
                    clientSocket = null;

                }
                Debug.WriteLine(e.ToString());


            }
        }

        private void Window_Closed(object sender, EventArgs e)

        {
            //关闭所有客户端的连接
            foreach (var socket in clientList.Values)
            {
                socket.Close();
            }
            //清空字典
            clientList.Clear();
            //窗口关闭停止服务
            isListen = false;
            if (severSocket != null)
            {
                severSocket.Close();
                severSocket = null;
            }

        }
    }
}
